//
//  SCCameraPhotoViewController.m
//  lg_zhinengbeikao_english
//
//  Created by Chao Sheng on 2021/12/13.
//  Copyright © 2021 zhukai. All rights reserved.
//

#import "SCCameraPhotoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SCClipImageView.h"
#import <CoreMotion/CoreMotion.h>

@interface SCCameraPhotoViewController ()

@property (nonatomic, strong) UIToolbar *toolBar;

//裁剪框
@property (nonatomic, strong) SCClipImageView *clipView;
//拍摄
@property (nonatomic, strong) UIButton *photoBtn;
//照片图像
@property (nonatomic, strong) UIImageView *imageView;
//旋转
@property (nonatomic, strong) UIButton *rotationBtn;
//重拍
@property (nonatomic, strong) UIButton *replayBtn;
//确定
@property (nonatomic, strong) UIButton *sureBtn;

@property (nonatomic, strong) AVCaptureSession *session;

//图片输出
@property (nonatomic, strong) AVCaptureStillImageOutput *imageOutput;

//后置摄像头输入
@property (nonatomic, strong) AVCaptureDeviceInput *backCameraInput;

//预览层
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

//原图
@property (nonatomic, strong) UIImage *originImage;

//当期图
@property (nonatomic, strong) UIImage *currentImage;

//toolBar高度
@property (nonatomic, assign) CGFloat toolBarH;

//imageView到顶部间距
@property (nonatomic, assign) CGFloat offsetY;
//imageView到左右间距
@property (nonatomic, assign) CGFloat offsetX;
//imageView宽度
@property (nonatomic, assign) CGFloat imgViewW;

@end

@implementation SCCameraPhotoViewController

- (instancetype)init{
    if (self = [super init]) {
        //初始化建立会话，获取摄像头
        [self.session setSessionPreset:AVCaptureSessionPresetPhoto];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = YES;
    self.view.backgroundColor = [UIColor blackColor];
    UIImage *bgImage = [SCPhotoTools imageLineWithColor:[[UIColor blackColor] colorWithAlphaComponent:1]];
    [self.navigationController.navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
    if (@available(iOS 15, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        appearance.shadowColor = [UIColor clearColor];
        appearance.backgroundImage = bgImage;
        self.navigationController.navigationBar.scrollEdgeAppearance = appearance;// 带scroll滑动的页面
        self.navigationController.navigationBar.standardAppearance = appearance;// 常规页面
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 44, 44);
    UIImage *image = [[UIImage sc_bundleImageNamed:@"LGQ-photoback"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    button.tintColor = [UIColor whiteColor];
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:image forState:UIControlStateHighlighted];
    [button setImageEdgeInsets:UIEdgeInsetsMake(6,-15,6,40)];
    [button addTarget:self action:@selector(didCancelClick) forControlEvents:UIControlEventTouchUpInside];
    button.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [self setupUI];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.session stopRunning];
    self.session = nil;
}

- (void)didCancelClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)setupUI {
    
    BOOL limited = [SCPhotoTools requestAuthorization:self type:@"camera"];
    if (limited==NO) {
        return;
    }
    
    //不同机型下的imageView尺寸和位置判断
    if(sc_PAD) {
        
        self.toolBarH = 156;
        self.offsetY = sc_NAVIGATION_HEIGHT;
        CGFloat imgViewH = sc_HEIGHT - sc_BOTTOMPADDING_HEIGHT - 156 - sc_NAVIGATION_HEIGHT;
        self.imgViewW = 0.75 * imgViewH;
        self.offsetX = (sc_WIDTH-self.imgViewW)/2;
        
    } else {
        self.imgViewW = sc_WIDTH;
        self.offsetX = 0;
        CGFloat offset = sc_HEIGHT - sc_BOTTOMPADDING_HEIGHT - 156 - sc_NAVIGATION_HEIGHT - sc_WIDTH/0.75;
        if (offset<=0) {
            self.toolBarH = sc_HEIGHT - sc_BOTTOMPADDING_HEIGHT - sc_NAVIGATION_HEIGHT - sc_WIDTH/0.75;
            self.offsetY = sc_NAVIGATION_HEIGHT;
        } else {
            self.toolBarH = 156;
            self.offsetY = offset + sc_NAVIGATION_HEIGHT;
        }
    }
    
    [self.view.layer addSublayer:self.previewLayer];
    [self.view addSubview:self.imageView];
    [self.view addSubview:self.toolBar];
    [self.view addSubview:self.clipView];
    [self.toolBar addSubview:self.photoBtn];
    [self.toolBar addSubview:self.sureBtn];
    [self.toolBar addSubview:self.rotationBtn];
    [self.toolBar addSubview:self.replayBtn];
    
    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.height.equalTo(@(sc_BOTTOMPADDING_HEIGHT+self.toolBarH));
    }];
    [self.photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.toolBar);
        make.centerY.equalTo(self.toolBar).offset(-sc_BOTTOMPADDING_HEIGHT/2);
        make.width.height.mas_equalTo(80);
    }];
    
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(self.offsetY);
        make.width.equalTo(@(self.imgViewW));
        make.height.equalTo(@(sc_WIDTH/0.75));
    }];
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.toolBar);
        make.centerY.equalTo(self.toolBar).offset(-sc_BOTTOMPADDING_HEIGHT/2);
        make.width.height.mas_equalTo(80);
    }];
    [self.replayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.sureBtn);
        make.width.height.equalTo(self.sureBtn);
        make.left.equalTo(self.sureBtn.mas_right).offset(50);
    }];
    [self.rotationBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.sureBtn);
        make.width.height.equalTo(self.sureBtn);
        make.right.equalTo(self.sureBtn.mas_left).offset(-50);
    }];
    
    if (![self.session isRunning]) {
        [self.session startRunning];
    }
}

#pragma mark - 拍摄
- (void)photoAction {
    //设置connection
    AVCaptureConnection* imageConnection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (imageConnection.supportsVideoOrientation) {
        imageConnection.videoOrientation = AVCaptureVideoOrientationPortrait;
    }
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:imageConnection completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
        if (!imageDataSampleBuffer || error) {
            NSLog(@"照片拍摄错误");
            return;
          }
        //获取原图
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        self.originImage = [[UIImage alloc] initWithData:imageData];
        NSLog(@"imageOrientation=%@",@(self.originImage.imageOrientation));
        UIImage *image = [UIImage changeOrientation:SCImageOrientationUp image:self.originImage];
        self.imageView.image = image;
        self.imageView.hidden = NO;
        self.previewLayer.hidden = YES;
        
        [self.session stopRunning];
        self.photoBtn.hidden = YES;
        self.sureBtn.hidden = NO;
        self.replayBtn.hidden = NO;
        self.rotationBtn.hidden = NO;
        self.clipView.hidden = NO;
        
        self.currentImage = image;
        
    }];
}

//重拍
- (void)replayAction {
    [self.session startRunning];
    self.photoBtn.hidden = NO;
    self.previewLayer.hidden = NO;
    
    self.sureBtn.hidden = YES;
    self.replayBtn.hidden = YES;
    self.rotationBtn.hidden = YES;
    self.clipView.hidden = YES;
    
    self.imageView.image = nil;
    self.imageView.hidden = YES;
}

//旋转
- (void)rotationAction {
    self.rotationBtn.selected =!self.rotationBtn.selected;
    
    if(self.rotationBtn.selected) {
        UIImage *image = [UIImage changeOrientation:SCImageOrientationLeft image:self.originImage];
        self.imageView.image = image;
        self.currentImage = image;
        
        CGRect originframe = CGRectMake(8+self.offsetX, 20+self.offsetY, self.imgViewW-16, self.imgViewW/0.75-40);
        CGFloat scale =  image.size.width/image.size.height;
        CGFloat h = self.imgViewW * scale;
        CGFloat offsetY = (self.clipView.frame.size.height - h)/2;
        CGFloat changedH = h - 20 * 2;
        
        CGRect frame = CGRectMake(originframe.origin.x,originframe.origin.y+offsetY+20, originframe.size.width, changedH);
        [self.clipView resetView:frame];
        
    } else {
        UIImage *image = [UIImage changeOrientation:SCImageOrientationUp image:self.originImage];
        self.imageView.image = image;
        self.currentImage = image;
        
        CGRect frame = CGRectMake(8+self.offsetX, 20+self.offsetY, self.imgViewW-16, self.imgViewW/0.75-40);
        [self.clipView resetView:frame];
    }
}

//确定，截取裁剪框范围图片
- (void)sureClip {
    //self.clipView的坐标转换到imageView上
    CGRect rect = [self.view convertRect:self.clipView.frame toView:self.imageView];

    //相对于原图的尺寸的缩放比例
    CGFloat scaleW = self.imageView.frame.size.width/self.imageView.image.size.width;
    CGFloat scaleH = self.imageView.frame.size.height/self.imageView.image.size.height;
    
    //在原图下裁剪图片
    UIImage *image = self.imageView.image;
    CGImageRef imageRef = image.CGImage;
    CGRect cutArea = CGRectMake(rect.origin.x / scaleW ,rect.origin.y / scaleH , rect.size.width / scaleW , rect.size.height / scaleH );
    CGImageRef cgimage = CGImageCreateWithImageInRect(imageRef, cutArea);
    UIImage *cutImage = [UIImage imageWithCGImage:cgimage];
    
    //输出结果
    self.imageView.image = cutImage;
    
    self.clipView.hidden = YES;
    
//    if (self.manager.ocrEnable) {
//        [MBProgressHUD showSCLoadind:@"正在识别，请稍后..."];
//        sc_weak(self);
//        [[SCHWCloudManager shareInstance] ocrImage:cutImage success:^(NSString * _Nonnull text) {
//            [MBProgressHUD hideSCHud];
//            [weakself setPhotoModel:cutImage Text:text isError:NO];
//
//        } failure:^(NSError * _Nonnull error) {
//            [MBProgressHUD hideSCHud];
//            [weakself setPhotoModel:cutImage Text:@"" isError:YES];
//        }];
//
//    } else {
//        [self setPhotoModel:cutImage Text:@"" isError:NO];
//    }
    [self setPhotoModel:cutImage Text:@"" isError:NO];
}

- (void)setPhotoModel:(UIImage*)image Text:(NSString*)text isError:(BOOL)isError{
    SCPhotoModel *model = [SCPhotoModel new];
    model.highQualityImage = image;
    model.tempImage = image;
    model.imgSize = image.size;
    model.date = [NSDate date];
    model.isSelected = YES;
    model.selectedIndex = self.manager.selectedArray.count+1;
    model.isCamera = YES;
    model.ocrText = text;
    model.ocrError = isError;
    
    [self.manager.selectedArray addObject:model];
    if (self.scCameraCompletion) {
        self.scCameraCompletion();
    }
    [self didCancelClick];
}

#pragma mark - 懒加载
- (UIToolbar *)toolBar {
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc] init];
        _toolBar.translucent = YES;
        _toolBar.barTintColor = [[UIColor blackColor] colorWithAlphaComponent:1];
    }
    return _toolBar;
}

- (AVCaptureSession *)session {
    if (!_session) {
        //添加后置摄像头与图片输出
        _session = [[AVCaptureSession alloc] init];
        if ([_session canAddInput:self.backCameraInput]) {
            [_session addInput:self.backCameraInput];
        }
        if ([_session canAddOutput:self.imageOutput]) {
            [_session addOutput:self.imageOutput];
        }
    }
    return _session;
}

- (AVCaptureStillImageOutput *)imageOutput {
    if (!_imageOutput) {
        _imageOutput = [[AVCaptureStillImageOutput alloc] init];
        _imageOutput.outputSettings = @{AVVideoCodecKey: AVVideoCodecJPEG};
    }
    return _imageOutput;
}

- (AVCaptureDeviceInput *)backCameraInput {
    if (!_backCameraInput) {
        AVCaptureDevice *devivce = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        _backCameraInput = [AVCaptureDeviceInput deviceInputWithDevice:devivce error:nil];
    }
    return _backCameraInput;
}

- (AVCaptureVideoPreviewLayer *)previewLayer {
    if (!_previewLayer) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        //摄像头朝向
        _previewLayer.connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        _previewLayer.frame = CGRectMake(0, sc_NAVIGATION_HEIGHT, sc_WIDTH, sc_HEIGHT-sc_NAVIGATION_HEIGHT-sc_BOTTOMPADDING_HEIGHT-self.toolBarH);
    }
    return _previewLayer;
}

- (UIButton *)photoBtn {
    if (!_photoBtn) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.layer.cornerRadius = 40;
        _photoBtn.layer.masksToBounds = true;
        _photoBtn.layer.borderWidth = 1;
        _photoBtn.layer.borderColor = UIColor.whiteColor.CGColor;
        _photoBtn.backgroundColor = [UIColor whiteColor];
        CAShapeLayer *circleLayer = [CAShapeLayer layer];
        circleLayer.frame = CGRectMake(2.5, 2.5, 75, 75);
        circleLayer.cornerRadius = 37.5;
        circleLayer.borderWidth = 2;
        circleLayer.borderColor = UIColor.blackColor.CGColor;
        [_photoBtn.layer addSublayer:circleLayer];
        [_photoBtn addTarget:self action:@selector(photoAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _photoBtn;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.hidden = YES;
        //_imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _imageView;
}

- (UIButton *)replayBtn {
    if (!_replayBtn) {
        _replayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_replayBtn setImage:[UIImage sc_bundleImageNamed:@"LGQ-replay"] forState:UIControlStateNormal];
        _replayBtn.hidden = YES;
        _replayBtn.layer.cornerRadius = 40;
        _replayBtn.layer.masksToBounds = true;
        _replayBtn.backgroundColor = [UIColor whiteColor];
        [_replayBtn addTarget:self action:@selector(replayAction) forControlEvents:UIControlEventTouchUpInside];
        [_replayBtn setImageEdgeInsets:UIEdgeInsetsMake(22, 22, 22, 22)];
    }
    return _replayBtn;
}

- (UIButton *)sureBtn {
    if (!_sureBtn) {
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureBtn setImage:[UIImage sc_bundleImageNamed:@"LGQ-playsuccess"] forState:UIControlStateNormal];
        _sureBtn.hidden = YES;
        _sureBtn.layer.cornerRadius = 40;
        _sureBtn.layer.masksToBounds = true;
        _sureBtn.backgroundColor = [UIColor colorWithRed:20.0/255 green:204.0/255 blue:51.0/255 alpha:1];
        [_sureBtn addTarget:self action:@selector(sureClip) forControlEvents:UIControlEventTouchUpInside];
        [_sureBtn setImageEdgeInsets:UIEdgeInsetsMake(15, 15, 15, 15)];
    }
    return _sureBtn;
}

- (UIButton *)rotationBtn {
    if (!_rotationBtn) {
        _rotationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rotationBtn setImage:[UIImage sc_bundleImageNamed:@"LGQ-rotation1"] forState:UIControlStateNormal];
        [_rotationBtn setImage:[UIImage sc_bundleImageNamed:@"LGQ-rotation2"] forState:UIControlStateSelected];
        _rotationBtn.hidden = YES;
        _rotationBtn.layer.cornerRadius = 40;
        _rotationBtn.layer.masksToBounds = true;
        _rotationBtn.backgroundColor = [UIColor whiteColor];
        [_rotationBtn addTarget:self action:@selector(rotationAction) forControlEvents:UIControlEventTouchUpInside];
        [_rotationBtn setImageEdgeInsets:UIEdgeInsetsMake(22, 22, 22, 22)];
    }
    return _rotationBtn;
}

- (SCClipImageView *)clipView {
    if (!_clipView) {
       
        CGRect frame = CGRectMake(8+self.offsetX, 20+self.offsetY, self.imgViewW-16, self.imgViewW/0.75-40);
        _clipView = [[SCClipImageView alloc] initWithFrame:frame];
        _clipView.hidden = YES;
    }
    return _clipView;
}

@end
